import styled from "styled-components";
import { Suspense, useState, useEffect, useRef } from "react";
import * as Three from "three";
import { Canvas, useLoader, ThreeElements } from "@react-three/fiber";
import { Loader } from "../Space/components/Loader";
import { Scene } from "./components/Scene";
import Stats from "./utils/stats.module.js";
import { AudioBars } from "./components/AudioBars.js";
import { Triangles, initValue } from "./types/index.js";
import { AudioLines } from "./components/AudioLines.js";
import { AddTriangle } from "./components/AddTriangle.js";
const Box = styled.div`
  width: 100%;
  height: 100%;
  position: relative;
`;

export function ViewsAudio() {
  const [initValue, setInitValue] = useState<initValue>({
    positionZ: 80,
    N: 256,
    clock: new Three.Clock(),
    scale: 1,
  });
  const BoxDom = useRef<HTMLDivElement>(null);
  const [Triangles, setTriangles] = useState<Triangles>([]);
  let stats = new Stats();
  /**
   *
   * @param value 添加角网
   */
  const setTriangle = (value: Triangles) => {
    setTriangles((val) => val.concat(value));
  };
  useEffect(() => {
    stats.dom.style.position = "absolute";
    BoxDom.current?.appendChild(stats.dom);
  }, []);
  const frameCallBack = () => {
    stats && stats.update();
  };
  return (
    <>
      <Box ref={BoxDom}>
        <Canvas>
          <Suspense fallback={<Loader />}>
            <Scene frameCallBack={frameCallBack}></Scene>
            {/* 音频柱子 */}
            <AudioBars
              {...initValue}
              radius={25}
              countData={initValue.N / 2}
            ></AudioBars>
            {/* 音频线 */}
            <AudioLines radius={25} countData={initValue.N / 2}></AudioLines>
            <AddTriangle
              Triangles={Triangles}
              setTriangles={setTriangle}
            ></AddTriangle>
          </Suspense>
        </Canvas>
      </Box>
    </>
  );
}
